const mongoose = require('mongoose')
const tools = require('./tools')
const Schema = mongoose.Schema
const Keyword = {}


const keywordSchema = Schema({
    text: { 
        type: String, 
        unique: true,
        required: [true, '请填写关键词！'],
        match: [/^[a-zA-Z0-9\u4e00-\u9fa5]{2,20}$/, '关键词是2~20个字母、数字、中文字符！'],
        minlength: [2, '关键词至少2个字符！'],
        maxlength: [20, '关键词最多20个字符！']
    },
    createUser: {
        type: Schema.Types.ObjectId,
        ref: 'users'
    },
    createTime: Date,
    ip: String
})


Keyword.Model = mongoose.model('keywords', keywordSchema)


Keyword.Model.on('index', err => {
    if (err) {
        console.error('集合 keywords 索引错误！', err)
    }
    else {
        console.log('集合 keywords 索引成功...')
    }
})


Keyword.list = function () {
    return new Promise(function (resolve, reject) {
        Keyword.Model.find().exec(function (err, models) {
            if (err) {
                reject(err)
            }
            else {
                resolve(tools.toDatas(models))
            }
        })
    })
}


module.exports = Keyword